package com.jiulong.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;





















import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;





















import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.jiulong.common.utils.HttpUtil;
import com.jiulong.common.utils.MD5Util;
import com.jiulong.common.utils.StringUtil;
import com.jiulong.dao.TAccountMapper;
import com.jiulong.dao.TGiftMapper;
import com.jiulong.dao.TProductMapper;
import com.jiulong.model.TAccount;
import com.jiulong.model.TAccountExample;
import com.jiulong.model.TFavorite;
import com.jiulong.model.TOrder;
import com.jiulong.model.TOrderExample;
import com.jiulong.model.TOrderdetail;
import com.jiulong.model.TOrderlog;
import com.jiulong.model.TOrdership;
import com.jiulong.model.TProduct;
import com.jiulong.service.AccountService;
import com.jiulong.service.OrderService;
import com.jiulong.service.ProductService;

@Controller  
public class IndexControlPhone extends BaseController{
	@Autowired
	ProductService productService;
	@Autowired
	TGiftMapper tGiftMapper;
	@Autowired
	com.jiulong.dao.TOrderMapper TOrderMapper;
	@Autowired
	TAccountMapper tAccountMapper;
	@Autowired
	TProductMapper tProductMapper;
	@Autowired
	AccountService accountService;
	@Autowired
	OrderService orderService;
	@Autowired
	ProductService ProductService;


	@RequestMapping("/ddzf2")
	public String ddzf2(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		String productId=request.getParameter("productId");
		
		if(productId==null||productId.equals("")){
			return "error1";
		}
		System.out.println(productId);
		//从预订页面拿来的跳转参数

		TProduct product =new TProduct();
		product= tProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
		BigDecimal price=product.getNowprice();
		BigDecimal yuanPrice=product.getPrice();
		String title=product.getTitle();
		String hotelName=product.getName();

		HttpSession session = request.getSession();
		session.setAttribute("productId", productId);
		session.setAttribute("price", price);	
		String openid1=null;
		try{
			openid1=session.getAttribute("openid1").toString();

		}catch(Exception e){
			return "login";
		}
		

		model.addAttribute("hotelName", hotelName);
		model.addAttribute("price", price);
		model.addAttribute("title", title);
		TAccount tAccount=	accountService.findAccountbyAname(openid1);
		System.out.println("我通过openid找到了用户的昵称！"+tAccount.getAccount());
		System.out.println(tAccount.getNickname());
		System.out.println("openid1"+openid1);
		model.addAttribute("yuanPrice", yuanPrice);
		
		String tel=tAccount.getTel();
		String cardNo=tAccount.getCardno();
		String nickname=tAccount.getNickname();
		model.addAttribute("nickname", nickname);
		model.addAttribute("tel", tel);
		model.addAttribute("cardNo", cardNo);	
		return "ddzf2";
	}
	
	
	
	
	//钟点房预订
	@RequestMapping("/ddzfZhong2")
	public String ddzfZhong2(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		try{
		String productName =new String(request.getParameter("productName").getBytes("iso8859-1"),"utf-8");
		TProduct product=ProductService.findProductbyId(productName);
		if(product==null){
			return "noSingleError";
		}
		String productId=product.getId().toString();
		BigDecimal price=product.getNowprice();
		BigDecimal yuanPrice=product.getPrice();
		String titleName=product.getIntroduce();
		String hotelName=product.getName();
		
		HttpSession session = request.getSession();
		session.setAttribute("productId", productId);
		session.setAttribute("price", price);	
		String openid1=null;
	try{
		openid1=session.getAttribute("openid1").toString();

	}catch(Exception e){
		return "login";
	}
		model.addAttribute("hotelName", hotelName);
		model.addAttribute("price", price);
		model.addAttribute("name", titleName);
		TAccount tAccount=	accountService.findAccountbyAname(openid1);
		model.addAttribute("yuanPrice", yuanPrice);	
		String tel=tAccount.getTel();
		String cardNo=tAccount.getCardno();
		String nickname=tAccount.getNickname();
		model.addAttribute("nickname", nickname);
		model.addAttribute("tel", tel);
		model.addAttribute("cardNo", cardNo);	
		}catch(Exception e){
			e.printStackTrace();
		}
		return "ddzfZhong1";
	}
	
	
	
	
	

	@RequestMapping("/hml2")
	public String hml2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "hml";
	}
	@RequestMapping("/hml122")
	public String hml12(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "pcview/hmlt12";
	}
	@RequestMapping("/test2")
	public String test2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "test";
	}
	@RequestMapping("/jdjm2")
	public String jdjm2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		return "jdjm";
	}
//生成订单
	@RequestMapping(value="/grzx12" ,method=RequestMethod.POST)
	public String grzx12(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		String account=request.getParameter("account");
		String user=request.getParameter("user");
		String endtime1=request.getParameter("endtime1");
		String starttime1 =request.getParameter("starttime1");
		//生成订单号
		long currentTimeMillis = System.currentTimeMillis();
	    String strReq =  currentTimeMillis + "jiulongWeiPayNo";
	    String out_trade_no = strReq; 
		String status="init";
	
		HttpSession session = request.getSession();
		String amount1=	 session.getAttribute("price").toString();
		 String total_fee1=String.valueOf((Double.valueOf(amount1)*100));
	     String total_fee = total_fee1.substring(0,total_fee1.indexOf("."));
		
		System.out.println(amount1);
	
		BigDecimal amount=new BigDecimal(amount1); 
		BigDecimal fee  =new BigDecimal(0);
		BigDecimal ptotal  =amount ;
		int quantity  =1;
		String 	paystatus= "n";
		String updateAmount="n";
		TOrder order=new TOrder();
	
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date=df.format(new Date());
			System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
			try{	order.setCreatedate(date);}catch(Exception e){
				e.printStackTrace();
			}
	
		order.setAccount(account);
		order.setUser(user);
		order.setEndtime1(endtime1);
		order.setStarttime1(starttime1);
		order.setStatus(status);
		order.setAmount(amount);
		order.setFee(fee);
		order.setPtotal(ptotal);
		order.setQuantity(quantity);
		order.setPaystatus(paystatus);
		order.setUpdateamount(updateAmount);
	
		
		
		String productId= session.getAttribute("productId").toString();
		TProduct product =new TProduct();
		product= tProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
		String productName=product.getName();
		String productIntroduce=product.getIntroduce();
		String imageUrl1=product.getPicture();
		String imageUrl="http://threeshop1.oss-cn-hangzhou.aliyuncs.com"+imageUrl1;
		//expresscode:此处作为产品名字
		order.setExpresscode(productName);
		//expressno:图片路径
		order.setExpressno(imageUrl);
		//expressnname:产品介绍
		order.setExpressname(productIntroduce);
		//remark：此处作为订单号的记录
		order.setRemark(out_trade_no);
		orderService.insertOrder(order);
		int orderId = 0;
	try{
		//获取订单id
		TOrderExample example=new TOrderExample();
		example.createCriteria().andRemarkEqualTo(out_trade_no);
		List<TOrder> orderList=TOrderMapper.selectByExample(example);
		orderList=TOrderMapper.selectByExample(example);
	    orderId=orderList.get(0).getId();
	}catch(Exception e){
		System.out.println("获取订单id异常！");
		e.printStackTrace();
	}
	//开始插入订单信息
		try{
	
		TOrderdetail detail=new TOrderdetail();
		detail.setOrderid(orderId);

		orderService.insertOrderDetail(detail);
		}catch(Exception sql){
			System.out.println("插入详细订单信息异常！");
			sql.printStackTrace();
		}

		

	String openid1=	session.getAttribute("openid1").toString()	;
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		
		
	TAccount tAccount=	accountService.findAccountbyAname(openid1);//12
	String score=tAccount.getScore().toString();
	String rank=tAccount.getRank();

	model.addAttribute("rank", rank);
	model.addAttribute("score", score);
	model.addAttribute("account", account);	
	
	
	String nickname=tAccount.getNickname();
	try{	
		//插入用户的信息
		TOrdership ship=new TOrdership();
		ship.setOrderid(String.valueOf(orderId));
		//查询手机号码和nickname
		ship.setPhone(tAccount.getTel());
		ship.setShipname(nickname);
		//remark作为入住日期
		ship.setRemark(starttime1);
		//tel作为离店日期
		ship.setTel(endtime1);
		//开始插入订单信息
			orderService.insertOrderShip(ship);
			}catch(Exception sql){
				System.out.println("插入详细订单ship信息异常！");
				sql.printStackTrace();
			}

	//插入日志信息
	try{
		TOrderlog log=new TOrderlog();
		log.setOrderid(String.valueOf(orderId));
		log.setAccount(nickname);
		log.setAccounttype("w");
		Calendar c = Calendar.getInstance();
		Date nowTime = c.getTime();
		System.out.println(nowTime);
		log.setCreatedate(nowTime);	
		log.setContent("【创建订单】用户创建订单。订单总金额："+amount);
		orderService.insertOrderLog(log);
	}catch(Exception e){
		System.out.println("订单日志插入失败！");
		e.printStackTrace();
	}
		
	try{
	List gift=orderService.findGiftbyId(nickname);
	
	List list=orderService.findOrderDetailByOpenid(nickname);
	model.addAttribute("detailList", list);
	 model.addAttribute("detailGift", gift);
	}catch(Exception e){
		e.printStackTrace();
	}
		return "grzxDing1";
	}
	@RequestMapping("/jdjs2")
	public String jdjs2(HttpServletRequest request,HttpServletResponse response) throws IOException, Exception{

			/*Calendar c = Calendar.getInstance();
			Date nowTime = c.getTime();
			System.out.println(nowTime);*/
		return "jdjs";
	}
	
	@RequestMapping("/grzx2")
	public String grzx2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "grzx";
	}
	
	@RequestMapping("/jdsp2")
	public String jdsp2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		
		return "jdsp";
	}
	@RequestMapping("/payAleady2")
	public String payAleady2(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		HttpSession session = request.getSession();

		String openid1=	session.getAttribute("openid1").toString();
		//String openid="ohx_wwmIaxOreZYa-RH8si7tVqYs";
		  TAccount tAccount=	accountService.findAccountbyAname(openid1);
		  String account=tAccount.getAccount();
			String score=tAccount.getScore().toString();
			String rank=tAccount.getRank();
			String nickname=tAccount.getNickname();
			model.addAttribute("rank", rank);
			model.addAttribute("score", score);
			model.addAttribute("account", nickname);
			List gift=orderService.findGiftbyId(nickname);
			List list=orderService.findOrderDetailByOpenidAleadyPay(nickname);
		 model.addAttribute("detailList", list);
		 model.addAttribute("detailGift", gift);
	    System.out.println();
		return "grzxDingWeiJie1";
	}
	//提交修改后的用户信息
	@RequestMapping(value="/xgxxa2" ,method=RequestMethod.POST)
	public String xgxxa2(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
	try{
		HttpSession session = request.getSession();
		//String openid="ohx_wwmIaxOreZYa-RH8si7tVqYs";
		String openid1=	session.getAttribute("openid1").toString();
	   String  nickname= request.getParameter("nickname");
	   String  cardNO= request.getParameter("cardNO");
	   String  tel= request.getParameter("tel");
	   TAccount tAccount=accountService.findAccountbyId(openid1);
	   tAccount.setNickname(nickname);
	   tAccount.setCardno(cardNO);
	   tAccount.setTel(tel);
	   tAccountMapper.updateByPrimaryKey(tAccount);
	 
		 model.addAttribute("nickname", nickname);
	    model.addAttribute("cardNO", cardNO);
	    model.addAttribute("tel", tel);
		}catch(Exception e){
			System.out.println("回显用户信息！");
			e.printStackTrace();
		}
		return "xgxx";
	}
//修改用户信息
	@RequestMapping("/xgxx2")
	public String xgxx2(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		HttpSession session = request.getSession();
		try{
		//String openid="ohx_wwmIaxOreZYa-RH8si7tVqYs";
		String openid1=session.getAttribute("openid1").toString();
		 TAccount tAccount=	accountService.findAccountbyId(openid1);
		 String nickname=tAccount.getNickname();
		 String cardNO=tAccount.getCardno();
		 String tel=tAccount.getTel();
		 model.addAttribute("nickname", nickname);
	    model.addAttribute("cardNO", cardNO);
	    model.addAttribute("tel", tel);
		}catch(Exception e){
			System.out.println("回显用户信息！");
			e.printStackTrace();
		}
		return "xgxx";
	}
	
	@RequestMapping(value="/login12" ,method=RequestMethod.POST)
	public String login1(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String account=request.getParameter("account");
		String password=request.getParameter("password");
		String encodePassword=	MD5Util.MD5Encode(password, "utf-8");
		
		TAccountExample example=new TAccountExample();
		example.createCriteria().andAccountEqualTo(account);
		List<TAccount> list=tAccountMapper.selectByExample(example);
		String test=list.toString();
		if("[]"==test){
			return "errorForTelRepeatRegister";

		}
		if(!encodePassword.equals(list.get(0).getPassword())){
			return "errorForTelRepeatRegister";
		}	
		HttpSession session=request.getSession();
		session.setAttribute("openid1", account);
		return "index";
	}
	@RequestMapping(value="/login2" ,method=RequestMethod.GET)
	public String yhhd(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "login";
	}
	
	@RequestMapping("/yhhd12")
	public String yhhd12(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "yhhd";
	}
	//删除订单，回复订单未支付页面
	@RequestMapping("/orderCancel2")
	public String orderCancel2(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		try{
		String orderId1=request.getParameter("orderId1");
		System.out.println(orderId1);
		TOrderMapper.deleteByPrimaryKey(Integer.parseInt(orderId1));
		System.out.println("我把未支付订单删除了！啊哈哈。。。");
		}catch(Exception e){
			e.printStackTrace();
		}
	 /*	response.setContentType("application/x-json");
    	PrintWriter out=response.getWriter();
    	JSONObject json=new JSONObject();
    	out.print(json.toString());
    	out.close(); */  
		
		HttpSession session = request.getSession();
		String openid1=session.getAttribute("openid1").toString();
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		  TAccount tAccount=accountService.findAccountbyAname(openid1);
		  String account=tAccount.getAccount();
			String score=tAccount.getScore().toString();
			String rank=tAccount.getRank();
			String nickname=tAccount.getNickname();
			model.addAttribute("rank", rank);
			model.addAttribute("score", score);
			model.addAttribute("account", nickname);
			
			List gift=orderService.findGiftbyId(nickname);
			List list=orderService.findOrderDetailByOpenid(nickname);
		 model.addAttribute("detailList", list);
		 model.addAttribute("detailGift", gift);
		
		return "grzxDing1";
	}
	
	@RequestMapping("/wjmm2")
	public String wjmm2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "wjmm";
	}
//手机端用户注册
	@SuppressWarnings("static-access")
	@RequestMapping(value="/register12",method=RequestMethod.POST)
	public String register12(HttpServletRequest request,HttpServletResponse response) throws IOException{

		String account=request.getParameter("account");
		MD5Util md=new MD5Util();
		String password1=request.getParameter("password");
		String newPassword=request.getParameter("newpassword");
		if(!password1.equals(newPassword)){

			return "error";
		}
		
		HttpSession session = request.getSession();
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		long currentTimeMillis = System.currentTimeMillis();
		 String strReq =  currentTimeMillis + "jiulongWeiPay";
	
		String openid1=strReq;
		String password=md.MD5Encode(password1, "utf-8");
		String cardNO=request.getParameter("cardNo");
		
		String nickname=request.getParameter("nickname");
		String tel=request.getParameter("tel");
		 TAccount tAccount1=accountService.findAccountbyTell(tel);
		 if(null!=tAccount1){
		if(tAccount1.getTel().equals(tel)){
			//手机端重复注册
			return "errorForTelRepeatRegister";
		}
	}
		String email=request.getParameter("email");
		
		TAccount tAccount=new TAccount();
			tAccount.setAccount(account);
			tAccount.setPassword(password);
			tAccount.setCardno(cardNO);
			tAccount.setTel(tel);
			tAccount.setEmail(email);
			tAccount.setNickname(nickname);
			tAccount.setOpenid(openid1);
		  tAccountMapper.insertSelective(tAccount);
		  	
		return "index";
	}	
	@RequestMapping("/register2")
	public String register2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "register";
	}
	
	@RequestMapping(value="/kfyd1",method=RequestMethod.GET)
	public String kfyd1(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{

        List list=productService.findProductByDefault(null);
    
        
        model.addAttribute("detailList", list);
        	return "kfyd1";
	}
	@RequestMapping(value="/kfyd1",method=RequestMethod.POST)
	public String postkfyd(String city,String startDate,String endDate,HttpServletRequest request,HttpServletResponse response,Model model) throws IOException, ParseException{
		String  publicDada =request.getParameter("publicDada");
		  
	        String a[] = publicDada.split(",");  
	        int breakfirst = 0 ; int park = 0 ; int meettingRoom = 0 ;int wifi = 0 ;int visitor = 0 ;
			for (String b : a) {
				
				if(b.equals("早餐")){
					 breakfirst=1;	
					
				}		
				if(b.equals("停车场")){
					 park=1;						 
				}
				if(b.equals("会议室")){
					 meettingRoom=1;		
				}
				if(b.equals("客房wifi")){
					 wifi=1;		
				}
				if(b.equals("接待外宾")){
					 visitor=1;		
				}
			}
	       
			System.out.println("breakfirst:"+breakfirst);  
	        System.out.println("park:"+park);  
	        System.out.println("meettingRoom:"+meettingRoom);  
	        System.out.println("wifi:"+wifi);  
	        System.out.println("visitor:"+visitor);
	 
	        
	        
	        
		String city1=null;
		if(!StringUtil.isBlank(city)){
			String c[]=city.split(" ");
			city=c[0];
			city1=c[1];
			if(city.length()>2){
				city=city.substring(0, 2);
			}
		}else{
			return "kfyd1";
		}
		Date sd=null;
		Date ed=null;
		if(!StringUtil.isBlank(startDate)&&!StringUtil.isBlank(endDate)){
			SimpleDateFormat sdf2  = new SimpleDateFormat("yyyy-MM-dd");
			sd=sdf2.parse(startDate);
			ed=sdf2.parse(endDate);
		}
		
		HashMap param=new HashMap();
		param.put("city", city);
		param.put("city1", city1);
		param.put("startDate",sd);
		param.put("endDate", ed);
	
		
		
		param.put("breakfirst", breakfirst);
		param.put("park", park);
		param.put("meettingRoom", meettingRoom);
	param.put("wifi", wifi);
		param.put("visitor", visitor);
		
	/*	Object o=breakfirst!=null?param.put("breakfirst",breakfirst.equals("on")?1:0):param.put("breakfirst", 0);
		o=park!=null?param.put("park",park.equals("on")?1:0):param.put("park", 0);
		o=meettingRoom!=null?param.put("meettingRoom",meettingRoom.equals("on")?1:0):param.put("meettingRoom", 0);
		o=wifi!=null?param.put("wifi",wifi.equals("on")?1:0):param.put("wifi", 0);
		o=visitor!=null?param.put("visitor",visitor.equals("on")?1:0):param.put("visitor", 0);*/
		
		List list=productService.findProductBysele(param);
		model.addAttribute("detailList", list);
		
		return "kfyd1";
	}
	@RequestMapping(value="/kfydLone2",method=RequestMethod.GET)
	public String kfyLone2(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{     
		List list=null;
		try{
		String productName =new String(request.getParameter("productName").getBytes("iso8859-1"),"utf-8");
	 	list=productService.findProductLone(productName);
	}catch(Exception e){
		e.printStackTrace();
	}
        model.addAttribute("detailList", list);
        	return "kfydLone2";
	}
	
	//进入订单页面未支付
		@RequestMapping("/selectOrder12")
		public String selectOrder(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			HttpSession session = request.getSession();
			String openid1=session.getAttribute("openid1").toString();
			//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
			  TAccount tAccount=accountService.findAccountbyAname(openid1);
			  String account=tAccount.getAccount();
				String score=tAccount.getScore().toString();
				String rank=tAccount.getRank();
				String nickname=tAccount.getNickname();
				model.addAttribute("rank", rank);
				model.addAttribute("score", score);
				model.addAttribute("account", nickname);
				
				List gift=orderService.findGiftbyId(nickname);
				List list=orderService.findOrderDetailByOpenid(nickname);
			 model.addAttribute("detailList", list);
			 model.addAttribute("detailGift", gift);

			return "grzxDing1";
		}
}
